package logic

import (
	"common/model"
	"context"
	order "order_server/proto"
)

// OrderList 订单列表展示
func (o *OrderServer) OrderList(ctx context.Context, req *order.OrderListRequest) (*order.OrderListResponse, error) {
	page := req.Pages
	if page <= 0 {
		page = 1
	}
	pageSize := req.PagePerNums
	if pageSize <= 0 {
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	// 获取订单列表
	orderList, total, err := model.GetOrderList(req.Uid, req.Status, offset, pageSize)
	if err != nil {
		return nil, err
	}

	// 构建返回数据
	var orderItems []*order.OrderListItem
	for _, orderItem := range orderList {
		info, err := model.GetProductInfo(orderItem.ProductId)
		if err != nil {
			return nil, err
		}
		orderItems = append(orderItems, &order.OrderListItem{
			Id:            orderItem.Id,
			OrderNo:       orderItem.OrderNo,
			UserId:        orderItem.UserId,
			ProductId:     orderItem.ProductId,
			OrderType:     orderItem.OrderType,
			OriginalPrice: orderItem.OriginalPrice,
			ActualPrice:   orderItem.ActualPrice,
			Quantity:      orderItem.Quantity,
			Status:        orderItem.Status,
			PaymentTime:   orderItem.PaymentTime.Format("2006-01-02 15:04:05"),
			CreatedAt:     orderItem.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:     orderItem.UpdatedAt.Format("2006-01-02 15:04:05"),
			ProductName:   info.StoreName,
			ProductImage:  info.Image,
		})
	}

	response := &order.OrderListResponse{
		Total: total,
		List:  orderItems,
	}
	return response, nil
}
